// 搜索生成器

function Creator(req, res, next){
  let page = req.query.currentPage || 1
  let pageSize = req.query.pageSize || 20
  const single = req.query.single || undefined
  let sort = req.query.sort || ''
  let want = req.query.want || ''
  let filter = req.query.filter || ''
  try {
    sort = sort ? JSON.parse(sort) : {}
    filter = filter ? JSON.parse(filter) : {}
    want = want ? JSON.parse(want): {}
  } catch (e) {
    return res.hasError('查询参数错误')
  }

  Object.keys(filter).forEach((item) => {
    let value = filter[item]
    if (value.indexOf('^') !== -1) {
      filter[item] = new RegExp(value, 'g')
    }
  })

  req.filter = {
    page: Math.abs(parseInt(page)),
    pageSize: Math.abs(parseInt(pageSize)),
    single: single,
    sort: sort,
    filter: filter,
    want: want,
  }
  console.log(req.filter)
  // 查询错误返回
  res.handleFindError = (err = []) => {
    res.status(500)
    return res.json({
      code: 500,
      msg: '服务器查询错误',
      result: err,
    })
  }
  next()
}


module.exports = Creator